<script setup>
import {onMounted, ref} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus';
import {Search, Refresh, Plus} from '@element-plus/icons-vue';
import {MenuStores} from '@/stores/MenuStores';
import MenuEdit from './MenuEdit.vue';

const menuStore = MenuStores();

const tableData = ref([]);
const searchForm = ref({
  name: '',
  path: '',
  isDelete: null
});

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const dialogVisible = ref(false);
const currentMenu = ref({});

const formatDateTime = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const fetchData = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value
    };

    await menuStore.list(params);
    tableData.value = menuStore.MenuList;
    total.value = menuStore.pageInfo.total;

  } catch (error) {
    ElMessage.error('获取菜单列表失败: ' + (error.message || '未知错误'));
    console.error('API Error:', error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

const resetSearch = () => {
  searchForm.value = {
    name: '',
    path: '',
    isDelete: null
  };
  currentPage.value = 1;
  fetchData();
};

const handleAdd = () => {
  currentMenu.value = {};
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  currentMenu.value = {...row};
  dialogVisible.value = true;
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除菜单"${row.name}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    await menuStore.delete(row.id);
    ElMessage.success('删除成功');
    await fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'));
    }
  }
};

const handleSuccess = () => {
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="menu-management-container">
    <el-card shadow="hover" class="search-card">
      <div class="search-header">
        <h3>菜单查询</h3>
        <div class="search-actions">
          <el-button type="primary" @click="fetchData" :loading="loading">
            <el-icon class="el-icon--left">
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon class="el-icon--left">
              <Refresh/>
            </el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon class="el-icon--left">
              <Plus/>
            </el-icon>
            新增
          </el-button>
        </div>
      </div>

      <el-form :model="searchForm" label-width="100px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="菜单名称">
              <el-input v-model="searchForm.name" placeholder="请输入菜单名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="菜单路径">
              <el-input v-model="searchForm.path" placeholder="请输入菜单路径" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-select v-model="searchForm.isDelete" placeholder="请选择状态" clearable>
                <el-option label="正常" :value="0"/>
                <el-option label="已删除" :value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="hover" class="table-card">
      <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          stripe
          border
          highlight-current-row
      >
        <el-table-column label="ID" prop="id" width="80" align="center"/>
        <el-table-column label="菜单名称" prop="name" width="150" align="center"/>
        <el-table-column label="菜单路径" prop="path" width="150" align="center"/>
        <el-table-column label="图标标识" prop="icon" width="200" align="center"/>
        <el-table-column label="关联权限" prop="aclId" width="100" align="center"/>
        <el-table-column label="父菜单" prop="parentId" width="80" align="center"/>
        <el-table-column label="状态" prop="isDelete" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isDelete === 0 ? 'success' : 'danger'">
              {{ scope.row.isDelete === 0 ? '正常' : '已删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdTime" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
                  :disabled="scope.row.isDelete === 1"
              >
                编辑
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                  :disabled="scope.row.isDelete === 1"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <MenuEdit
        v-model:visible="dialogVisible"
        :menu-data="currentMenu"
        @success="handleSuccess"
    />
  </div>
</template>

<style scoped>
.menu-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-header h3 {
  margin: 0;
  color: #409EFF;
  font-size: 18px;
}

.search-form {
  margin-top: 10px;
}

.table-card {
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.el-button {
  padding: 8px 15px;
}
</style>